import tkinter as tk
from tkinter import font, messagebox
import os
import sys

# 读取GA_chs.exe文件的内容
def read_exe():
    try:
        with open('GA_chs.exe', 'rb') as file:
            content = file.read()
        return content
    except FileNotFoundError:
        messagebox.showerror("错误", "请把本程序与GA_chs放至同一目录")
        sys.exit()

# 将指定地址的内容转换为GBK编码文字，并处理结尾的00
def convert_to_gbk(content, start, end):
    data = content[start:end]
    hex_string = data.hex()
    i = len(hex_string) - 2
    while i >= 0 and hex_string[i:i+2] == '00':
        i -= 2
    cleaned_hex = hex_string[:i+2] if i >= 0 else ''
    cleaned_data = bytes.fromhex(cleaned_hex)
    return cleaned_data.decode('gbk', errors='ignore')

# 修改指定地址的内容
def modify_exe(content, font_name, start1, end1, start2, end2):
    gbk_encoded = font_name.encode('gbk')
    hex_string = gbk_encoded.hex()
    if len(hex_string) > 26:
        raise ValueError("字体名称过长，无法修改")
    hex_string += '0' * (26 - len(hex_string))
    modified_content = content[:start1] + bytes.fromhex(hex_string) + content[end1:]
    modified_content = modified_content[:start2] + bytes.fromhex(hex_string) + modified_content[end2:]
    return modified_content

# 保存修改后的文件
def save_exe(content):
    with open('GA_chs.exe', 'wb') as file:
        file.write(content)

# 更新窗口标题
def update_title(font_name, font_count):
    root.title(f"选择字体 - 当前字体: {font_name} - 可选字体数量: {font_count}")

# 获取系统上的所有字体并排序
def get_sorted_fonts():
    fonts = [font for font in font.families() if not font.startswith('@')]
    chinese_fonts = sorted([font for font in fonts if any(char.isalpha() and not char.isascii() for char in font)])
    ms_fonts = sorted([font for font in fonts if font.startswith('MS')])
    other_fonts = sorted([font for font in fonts if font not in chinese_fonts and font not in ms_fonts])
    return chinese_fonts + ms_fonts + other_fonts

# 读取GA_chs.exe文件的内容
content = read_exe()

# 将地址e23a8至e23b4之间的内容转换为GBK编码文字
font_name_display = convert_to_gbk(content, 0xe23a8, 0xe23b4 + 1)

# 创建主窗口
root = tk.Tk()
root.title("选择字体")

# 使主窗口居中显示
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_width = 600
window_height = 400
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")



# 获取系统上的所有字体并添加到列表框中
sorted_fonts = get_sorted_fonts()
font_list = tk.Listbox(root, font=("Arial", 12), width=50, height=15)
font_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(root, orient="vertical")
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar.config(command=font_list.yview)
font_list.config(yscrollcommand=scrollbar.set)

font_count = 0
for font in sorted_fonts:
    gbk_encoded = font.encode('gbk')
    hex_string = gbk_encoded.hex()
    if len(hex_string) <= 26:
        font_list.insert(tk.END, font)
        font_count += 1

# 更新窗口标题
update_title(font_name_display, font_count)

# 创建一个按钮，用于更新标签的字体
def select_font():
    # 获取当前选中的字体索引
    selected_index = font_list.curselection()
    if selected_index:
        selected_font = font_list.get(selected_index)
        try:
            modified_content = modify_exe(content, selected_font, 0xe23a8, 0xe23b4 + 1, 0xe6df8, 0xe6e04 + 1)
            save_exe(modified_content)
            root.destroy()  # 关闭主窗口
            messagebox.showinfo("成功", "修改成功")
        except Exception as e:
            messagebox.showerror("错误", str(e))
    else:
        messagebox.showwarning("警告", "请先选择一个字体")

select_button = tk.Button(root, text="选择字体", command=select_font)
select_button.pack(pady=10)

# 运行主循环
root.mainloop()